package com.epsi.mightymaps.ntwrk;

import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;

public abstract class NetworkRunnable implements Runnable {
	private static final String TAG = NetworkRunnable.class.getSimpleName();

	private static final String ENCODING = "UTF-8";
	private static final int RESPONSE_BA_SIZE = 256;

	public static final String ADDRESS = "http://www.fakesite.com/";
	protected static final String PRM_USERID = "user_id";
	protected static final String PRM_LATITUDE = "lat";
	protected static final String PRM_LONGITUDE = "lng";

	private static final int OK = 10;
	private static final int ERROR = 11;

	public static int USER_ID;

	private NetworkListener listener;

	private Handler hdl = new Handler() {
		public void handleMessage(final Message pMsg) {
			switch (pMsg.what) {
			case OK:
				NetworkRunnable.this.listener
						.notifyReceivedMsg((String) pMsg.obj);
				break;
			case ERROR:
				NetworkRunnable.this.listener.notifyError((Exception) pMsg.obj);
				break;
			default:
				Log.e(TAG, "Unhandled case : " + pMsg.what);
				break;
			}
		}
	};

	public NetworkRunnable(final NetworkListener pListener) {
		this.listener = pListener;
	}

	protected void doGet(final String pUrl, final List<NameValuePair> pParams) {
		String url = pUrl + '?' + URLEncodedUtils.format(pParams, ENCODING);

		HttpGet get = new HttpGet(url);
		HttpClient client = new DefaultHttpClient();
		StringBuffer buffer = new StringBuffer();

		try {
			HttpResponse response = client.execute(get);
			InputStream inputStream = response.getEntity().getContent();
			byte[] data = new byte[RESPONSE_BA_SIZE];
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len, ENCODING).replaceAll(
						"\r", ""));
			}
			inputStream.close();

			Message message = new Message();
			message.what = OK;
			message.obj = buffer.toString();
			this.hdl.sendMessage(message);

		} catch (Exception e) {
			Log.w(TAG, "Error while getting infos", e);
			Message message = new Message();
			message.what = ERROR;
			message.obj = e;
			this.hdl.sendMessage(message);
		}

	}

	public static void initUserID(final Context pContext) {
		TelephonyManager telManager = (TelephonyManager) pContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		USER_ID = telManager.getDeviceId().hashCode();
	}
}
